package com.worldtolearn.order.dao;

import java.util.List;
import java.util.Set;

import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;
import org.springframework.stereotype.Repository;

import com.worldtolearn.order.entity.Order;
import com.worldtolearn.order.entity.OrderLine;
import com.worldtolearn.user.entity.User;



@Repository
public class OrderDaoImpl extends HibernateDaoSupport  implements IOrderDAO {
	


	@Autowired
	public void init(SessionFactory factory) {
	    setSessionFactory(factory);
	}

	@Override
	public void createOrder(Order order) {
		System.out.println("getHibernateTemplate() : "+getHibernateTemplate());
		System.out.println("$$$$$$$$$$$$$$*************************************getHibernateTemplate() order: "+order.getPerson().getIdPerson());
		User  u = getHibernateTemplate().get(User.class, order.getPerson().getIdPerson());
		System.out.println("getHibernateTemplate() after: ");
		order.setPerson(u);
		Set<OrderLine> setLines = order.getOrderLines();
		for (OrderLine lines : setLines) {
			getHibernateTemplate().save(lines);
		}
		getHibernateTemplate().save(order);
		System.out.println("getHibernateTemplate() afterafterafter: ");

	}

	@Override
	public void deleteOrder(Order Order) {
		// TODO Auto-generated method stub

	}

	@SuppressWarnings("unchecked")
	@Override
	public List<Order> getLastOrder(int idPerson) {
		
		return  getHibernateTemplate().findByNamedParam
				("select a from Order a where a.person.idPerson like :idPerson order by a.person.idPerson desc 1", "idPerson", idPerson);
		
		
	}

	@Override
	public List<OrderLine> getLineOrderByOrder(Order order) {
		System.out.println("getLineOrderByOrder  requiered");
		return null;
	}

}
